package cn.zcltd.btg.httpsession.servlet.interceptor;

import cn.zcltd.btg.httpsession.kit.SessionKit;
import cn.zcltd.btg.httpsession.servlet.BTGHttpServletRequest;
import cn.zcltd.btg.sutil.EmptyUtil;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;

import javax.servlet.http.HttpSession;

/**
 * 注意：此intercepter优先级必须大于其他业务处理的intercepter
 * BTGHttpSessionRequest替换interceptor
 */
public class BTGHttpSessionInterceptor implements Interceptor {
    @Override
    public void intercept(Invocation invocation) {
        Controller targetController = invocation.getController();

        targetController.setHttpServletRequest(new BTGHttpServletRequest(targetController.getRequest()));//替换自定义session的request扩展

        //根据是否开启简单单点登录设置默认cookie path
        if (SessionKit.isDisableSimpleSSO()) {
            SessionKit.setSessionCookiePath(targetController.getRequest().getContextPath() + "/");
        }

        //自动设置session cookie
        HttpSession session = targetController.getSession(false);
        if (EmptyUtil.isEmpty(session)) {
            session = SessionKit.getNewSession();
        }

        targetController.setCookie(SessionKit.getSessionIdKey(), session.getId(), session.getMaxInactiveInterval(), SessionKit.getSessionCookiePath());

        invocation.invoke();
    }
}